from random import randrange

from django.core.mail import send_mail

from blog.models import EmailVerifyCode
from iblog.settings import EMAIL_FROM


def get_random_code(code_length):
    code_source = '1234567890'
    code = ''
    for i in range(code_length):
        str = code_source[randrange(0, len(code_source))]
        code += str
    return code


def send_email_code(email, send_type):
    code = get_random_code(4)
    a = EmailVerifyCode()
    a.email = email
    a.send_type = send_type
    a.code = code
    a.save()

    send_title = ''
    send_body = ''
    if send_type == 1:
        send_title = '爱博客|www.iblog.cool '
        send_body = '尊敬的用户，请尽快去激活您的密码，邮箱验证码为：' + code
        send_mail(send_title, send_body, EMAIL_FROM, [email])
    if send_type == 2:
        send_title = '爱博客|www.iblog.cool '
        send_body = '尊敬的用户，请尽快去重置您的密码，邮箱验证码为：' + code
        send_mail(send_title, send_body, EMAIL_FROM, [email])
